﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using XWG.Framework.AuthUtility;
using XWG.JWBST.JWBSTEntity;
using XWG.JWBST.JWBSTBLL;
using XWG.Framework.AuthBLL;

namespace XWG.JWBST.JWBSTManagementApp.ZPXXCJ
{
    public partial class DataImp : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

            }
        }

        protected void btn_Upload_Click(object sender, EventArgs e)
        {
            if (this.FileExecl.HasFile)
            {
                try
                {
                    var emptyNum = 0;
                    string filetype = System.IO.Path.GetExtension(FileExecl.FileName);
                    if (filetype == ".xls" || filetype == ".xlsx")
                    {
                        string filepath = Server.MapPath("//ZPXXCJ/UploadExcel") + "\\" + FileExecl.FileName;
                        FileExecl.SaveAs(filepath);
                        DataTable dt = Excel.DataTableFromExcel(filepath, 0, 0);
                        if (dt != null)
                        {
                            int ImpNum = dt.Rows.Count;
                            if (ImpNum > 0)
                            {
                                var emptyMsg = "";
                                int succNum = ExportMes(dt, out emptyNum);
                                if (emptyNum > 0)
                                {
                                    emptyMsg = "反馈内容为空的记录被忽略，共计" + emptyNum.ToString() + "条。";
                                }
                                Logger(succNum, filepath);
                                JsSet.Alert(this, "已完成数据导入,共导入诈骗信息" + succNum + "条数据。" + emptyMsg);
                            }
                            else
                            {
                                //无内容
                                JsSet.Alert(this, "已选择的Excel文件中无导入数据");
                            }
                        }
                    }
                    else
                    {
                        //格式错误
                        JsSet.Alert(this, "请选择正确的Excel文件（.xls或.xlsx）");
                    }
                }
                catch (Exception ex)
                {
                    JsSet.Alert(this, "导入过程中出现错误：" + ex.Message.ToString() + ",请联系管理员");
                }
            }
            else
            {
                //选择文件
                JsSet.Alert(this, "请选择要导入的Excel文件");
            }
        }

        private static int ExportMes(DataTable dt, out int emptyNum)
        {
            emptyNum = 0;
            DataTable cdt = new DataTable();
            var mUser = AppOrganizatiOnUserBLL.Load(HttpContext.Current.Session["UserID"].ToString());
            int SuccNum = 0;
            ResultModel mResultModel = new ResultModel();
            DataRow dr = null;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dr = dt.Rows[i];
                //id非空
                if (!string.IsNullOrEmpty(dr[0].ToString()))
                {
                    var tempGuid = Guid.NewGuid();
                    //id必须是guid
                    if (Guid.TryParse(dr[0].ToString(), out tempGuid))
                    {
                        //对象必须存在，不存在跳过
                        var feback = TbBstFraudFeedbackBLL.Load(dr[0].ToString());
                        if (feback != null)
                        {
                            if (string.IsNullOrEmpty(dr[5].ToString()))
                            {
                                emptyNum++;
                                continue;
                            }
                            feback.Result = dr[5].ToString();
                            feback.Remark = dr[6].ToString();
                            feback.Resultdate = DateTime.Now;
                            feback.Resultstatus = "2";
                            switch (mUser.Bz5)
                            {
                                case "1":
                                    feback.Ydrs = "2";
                                    break;
                                case "2":
                                    feback.Ltrs = "2";
                                    break;
                                case "3":
                                    feback.Dxrs = "2";
                                    break;
                            }
                            mResultModel = TbBstFraudFeedbackBLL.Update(feback, "", false);
                            if (mResultModel.ISSucceed)
                            {
                                SuccNum += 1;
                            }
                        }

                        //每家运营商每个纪录仅能反馈一次   同运营商第二次插入则为更新
                        cdt = TbBstFraudFeedbackStatusBLL.CheckFeedbackStatus(tempGuid.ToString(), mUser.UserId);
                        if (cdt != null && cdt.Rows.Count > 0)
                        {
                            for (int j = 0; j < cdt.Rows.Count; j++)
                            {
                                //更新
                                TbBstFraudFeedbackStatus feebStatus = new TbBstFraudFeedbackStatus();
                                feebStatus.Result = dr[5].ToString();
                                feebStatus.Resultdate = DateTime.Now;
                                feebStatus.Id = cdt.Rows[j]["ID"].ToString();
                                TbBstFraudFeedbackStatusBLL.UpdateStatus(feebStatus);
                            }

                        }
                        else
                        {
                            //插入
                            TbBstFraudFeedbackStatus feebStatus = new TbBstFraudFeedbackStatus();
                            feebStatus.Id = Guid.NewGuid().ToString();
                            feebStatus.Result = dr[5].ToString();
                            feebStatus.Resultstatus = "2";
                            feebStatus.Resultdate = DateTime.Now;
                            feebStatus.Feedbackid = feback.Id;
                            feebStatus.Movesign = "0";
                            feebStatus.Operatorsid = mUser.UserId;
                            feebStatus.Operatorscode = mUser.Bz5;
                            feebStatus.Insideid = feback.Insideid;
                            TbBstFraudFeedbackStatusBLL.Insert(feebStatus, "", false);
                        }
                    }
                }
            }
            return SuccNum;
        }

        private static void Logger(int num, string filepath)
        {
            var mUser = AppOrganizatiOnUserBLL.Load(HttpContext.Current.Session["UserID"]);
            //type  0  下载  1上传
            TbBstFraudOperationhistory his = new TbBstFraudOperationhistory();
            his.Id = Guid.NewGuid().ToString();
            his.Operationtype = "1";
            his.Username = mUser.UserName;
            his.Operatorscode = mUser.Bz5;

            switch (his.Operatorscode)
            {
                case "1":
                    his.Operatorsname = "中国移动";
                    break;
                case "2":
                    his.Operatorsname = "中国联通";
                    break;
                case "3":
                    his.Operatorsname = "中国电信";
                    break;
                case "4":
                    his.Operatorsname = "其他";
                    break;
                default:
                    his.Operatorsname = mUser.UserName;
                    break;
            }
            his.Records = num;
            his.Filepath = filepath;
            his.Createdate = DateTime.Now;

            TbBstFraudOperationhistoryBLL.Insert(his, "", false);
        }
    }
}